import { fileURLToPath, URL } from 'node:url'
import { defineConfig, loadEnv, ConfigEnv, UserConfig } from 'vite'
import { getVitePlugins } from './build/plugins'
import { getBuildConfig } from './build/build'

export default defineConfig(({ mode }: ConfigEnv): UserConfig => {
  // 加载环境变量
  const env = loadEnv(mode, process.cwd())
  // 当前执行 node 命令时文件夹的地址 工作目录
  const root = process.cwd()

  return {
    root: root,
    // 插件
    plugins: getVitePlugins(mode),

    // 别名配置
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
      },
    },

    // 服务器配置
    server: {
      port: Number(env.VITE_API_BASE_PORT),
      host: '0.0.0.0',
      open: false,
      proxy: env.VITE_USE_PROXY === 'true' ? {
        [env.VITE_PROXY_URL]: {
          target: env.VITE_API_BASE_URL,
          changeOrigin: true,
          rewrite: (path) => path.replace(new RegExp(`^${env.VITE_APP_PROXY_URL}`), '')
        }
      } : undefined
    },

    // 构建配置
    build: getBuildConfig(mode),

    // 预构建优化大型依赖加载性能
    optimizeDeps: {
      // 强制预构建的依赖
      include: ['lodash-es', 'axios', 'element-plus'],
      // 排除的依赖
      exclude: []
    },

    // CSS 预处理器配置
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: '@use "@/styles/variables.scss" as *;',
          // 暂时禁用即将被废弃的 API 警告
          silenceDeprecations: ["legacy-js-api"],
        }
      }
    }
  }
})
